package com.test.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.test.ssm.pojo.Role;
import com.test.ssm.pojo.RoleCriteria;
import com.test.ssm.service.GameService;
import com.test.ssm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RoleController {
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private GameService gameService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("role.html")
    public String page(Model model) {
        model.addAttribute("games", gameService.getAllGame());
        return "role";
    }

    @RequestMapping("search.html")
    @ResponseBody
    public Map<String, Object> search(RoleCriteria criteria, int page, int limit) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        PageInfo<Role> pageInfo = roleService.getRoleList(criteria, page, limit);
        result.put("count", pageInfo.getTotal());
        result.put("data", pageInfo.getList());
        return result;
    }

    @RequestMapping("go_update.html")
    @ResponseBody
    public Role getRole(Integer id){
        return roleService.getRoleById(id);
    }

    @RequestMapping("update.html")
    @ResponseBody
    public Map<String,Object> update(Role role){
        Map<String,Object> result=new HashMap<>();
        try {
            roleService.update(role);
            result.put("status",true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message",e.getMessage());
            result.put("status",true);
        }
        return result;
    }

}
